package com.malguy.controllers;

import com.malguy.controllers.groups.ValidationGroup1;
import com.malguy.controllers.groups.ValidationGroup2;
import com.malguy.entity.HandlerMvc;
import com.malguy.entity.student;
import com.malguy.entity.student1;
import com.malguy.entity.user;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * @author malguy-wang sir
 * @create ---
 */
@Controller
public class myController {
    @RequestMapping("/bonjour")
    public void bonjour(HttpServletRequest req, HttpServletResponse resp) {
        try {
            resp.getWriter().write("bonjour");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/bonsoir")
    public void bonsior(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.getRequestDispatcher("/jsp/bonsoir.jsp").forward(req, resp);
    }

    @RequestMapping("/he1")
    public void he1(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.sendRedirect("/jsp/bonsoir.jsp");
    }

    @RequestMapping("/he2")
    public void he2(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setStatus(302);//设置状态码
        resp.setHeader("location", "/jsp/bonsoir.jsp");
    }

    @RequestMapping("/he3")
    public void he3(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html; charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("你好,大师");
        writer.flush();
        writer.close();
    }

    @RequestMapping("/he4")
    public String he4(Model model) {
        model.addAttribute("username", "h7r");
        return "hh";//去寻找一个叫hh的视图,之前写过的
    }

    @RequestMapping("/he5")
    public String he5() {
        return "forward:/jsp/hi.jsp";
    }

    @RequestMapping("/he6")
    public String he6() {
        return "redirect:/he4";
    }

    @ResponseBody
    @RequestMapping(value = "/h6", produces = "text/html; charset=utf-8")
    public String h6() {
        return "为什么不成功";
    }

    @RequestMapping("/addBook")
    public String addBook() {
        return "addBook";
    }

    //    @RequestMapping(value = "/doAdd",method = RequestMethod.POST)
//    @ResponseBody
//    public void doAdd(@RequestParam(value = "name",defaultValue = "malred",required = true) String userName,
//                      String sex, int age){//显示结果
//        System.out.println(userName);
//        System.out.println(sex);
//        System.out.println(age);
//    }
    @RequestMapping(value = "/doAdd", method = RequestMethod.POST)
    @ResponseBody
    public void doAdd(user user, HttpServletResponse resp) {//显示结果
        System.out.println(user);
        try {
            resp.setContentType("text/html; charset=utf-8");
            resp.getWriter().write(user.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/map")
    public String map() {
        return "map";
    }

    @RequestMapping("/mvc")
    public void mvc(HandlerMvc handlerMvc, HttpServletResponse res) {
        try {
            res.getWriter().write(handlerMvc.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/addStu")
    @ResponseBody
    public void addStu(@Validated(ValidationGroup1.class) student student, BindingResult result) {
        if (result != null) {
            //校验未通过,获取所有异常并显示
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError objectError : list) {
                System.out.println(objectError.getObjectName() + ":" + objectError.getDefaultMessage());
            }
        }
    }

    @RequestMapping("/addStu2")
    public String addStu2(Integer id, String name, Integer age, String email, Model model) {
        model.addAttribute("id", id);
        model.addAttribute("name", name);
        model.addAttribute("age", age);
        model.addAttribute("email", email);
        if (id == null || name == null || name.length() < 2 || name.length() > 10 || age > 100 || email == null)
            return "addStu2";
        return "student";
    }

    @RequestMapping("/addStu3")
    public String addStu3(@Validated(ValidationGroup1.class) @ModelAttribute("stu") student student, BindingResult bindingResult) {//加上注解，进行数据校验
        System.out.println(student);//validated注解后加上分组，只会校验对应分组，@modelattribute可以重命名，这样对应jsp的参数就可以用 xxx.属性 传参
        if (bindingResult.hasErrors()) {
            List<ObjectError> list = bindingResult.getAllErrors();
            for (ObjectError obj : list) {
                System.out.println("error = " + obj.getDefaultMessage());
            }
            return "addStu3";
        }
        return "hello";
    }

    //当前controller返回数据时,把当前的map一起返回给前端,"info"表示返回的数据的key
    @ModelAttribute("info")
    public Map<String, Object> info() {
        Map<String, Object> map = new HashMap<>();
        map.put("username", "root");
        map.put("myName", "malred");
        return map;
    }

    @RequestMapping("/hello")
    public String hello() {
        return "hello";
    }

    @RequestMapping("/stu")
    @ResponseBody
    public student stu(student stu) {
        return stu;
    }

    @RequestMapping("/stu1")
    @ResponseBody
    public List<student> stu1() {
        List<student> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(new student(i, "a" + i, i + 10, "200" + i + "@qq.com"));
        }
        return list;
    }

    @RequestMapping("/stu2")
    @ResponseBody
    public student1 stu2() {
        student1 student1 = new student1();
        student1.setName("K");
        student1.setBirth(new Date());
        student1.setEmail("123@qq.com");
        student1.setId(1);
        return student1;
    }

    @RequestMapping("/s")
    @ResponseBody
    public student s(student student) {
        return student;
    }
    @GetMapping("/path/{id}/{name}")
    @ResponseBody
    public student path(@PathVariable Integer id,@PathVariable String name){
        student student = new student(id,name,18,"test@qq.com");
        return student;
    }
}

